package com.neusoft.nep.admin.controller;
import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.admin.entity.AqiData;
import com.neusoft.nep.admin.entity.Feedback;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class AppointViewController {
    private Stage dialog;
    private Feedback feedback;
    @FXML
    private TextField id;
    @FXML
    private TextField message;
    @FXML
    private TextField telephone;
    @FXML
    private TextField address;
    @FXML
    private TextField details;
    @FXML
    private TextField AQI;
    @FXML
    private TextField date;
    @FXML
    private TableView<Feedback> tableView;
    @FXML
    private ComboBox grid;
    public void initialize() {
       grid.getItems().addAll("张三", "李四", "王五");
    }
    public void setDialog(Stage dialog) {

        this.dialog = dialog;
    }
    public void back(){
        dialog.close();
    }
    public Feedback getFeedback() {
        return feedback;
    }
    public void setData(Feedback feedback) {
        this.feedback = feedback;
        id.setText(String.valueOf(feedback.getId()));
        message.setText(feedback.getName()+feedback.getSex()+feedback.getBornDate());
        telephone.setText(feedback.getTelephone());
        address.setText(feedback.getProvince()+feedback.getCity());
        details.setText(feedback.getDetails());
        AQI.setText(String.valueOf(feedback.getAQI()));
        date.setText(String.valueOf(feedback.getDate()));
    }
    public void LDappoint(){
        try{ // 加载FXML文件
            FXMLLoader fxmlLoader = new FXMLLoader();
            URL url = getClass().getResource("../view/LDappointView.fxml");
            fxmlLoader.setLocation(url);
            // 加载视图
            Parent root = fxmlLoader.load();
            // 创建对话框
            Stage dialog = new Stage();
            dialog.setTitle("公众监督数据列表/公众监督数据详情");
            dialog.initModality(Modality.APPLICATION_MODAL);
            Scene scene = new Scene(root);
            dialog.setScene(scene);
            // 获取控制器并注入dialog引用（如果需要）
            LDappointViewController controller = fxmlLoader.getController();
            if (controller != null) {
                controller.setDialog(dialog);
                controller.setData(feedback);
            }
            // 显示对话框并等待关闭
            dialog.showAndWait();
        } catch (IOException ex) {
            System.err.println("加载FXML文件时出错: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
    public void appoint() {
        String addGrid=grid.getSelectionModel().getSelectedItem().toString();
        feedback.setGrid(addGrid);
        if(addGrid=="张三"){
            Map<String, Feedback> userMap = FileUtils.readMapObject("feedback.txt");
            userMap.put(feedback.getId(), feedback);
            FileUtils.writeMapObject("feedback1.txt", userMap);
            System.out.println("成功传给张三");
        }else if(addGrid=="李四"){
            Map<String, Feedback> userMap = FileUtils.readMapObject("feedback.txt");
            userMap.put(feedback.getId(), feedback);
            FileUtils.writeMapObject("feedback2.txt", userMap);
            System.out.println("成功1传给李四");
        }else{
            Map<String, Feedback> userMap = FileUtils.readMapObject("feedback.txt");
            userMap.put(feedback.getId(), feedback);
            FileUtils.writeMapObject("feedback3.txt", userMap);
            System.out.println("成功传给王五");
        }
        System.out.println(feedback.getId()+" "+feedback.getName()+" "+feedback.getSex()+" "+feedback.getBornDate()+" "+feedback.getTelephone()+" "+feedback.getProvince()+" "+feedback.getCity()+feedback.getDetails()+" "+feedback.getAQI()+" "+feedback.getDate()+" "+feedback.getGrid());
    }

    public static class AQIAdminViewController {

        @FXML
        private TableView<AqiData> aqiTable;

        @FXML
        private TableColumn<AqiData, String> idColumn;
        @FXML
        private TableColumn<AqiData, String> provinceColumn;
        @FXML
        private TableColumn<AqiData, String> cityColumn;
        @FXML
        private TableColumn<AqiData, String> levelColumn;
        @FXML
        private TableColumn<AqiData, String> dateColumn;
        @FXML
        private TableColumn<AqiData, String> timeColumn;
        @FXML
        private TableColumn<AqiData, String> gridStaffColumn;
        @FXML
        private TableColumn<AqiData, String> reporterColumn;
        @FXML
        private TableColumn<AqiData, String> actionColumn;



        @FXML
        public void initialize() {

            idColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getId()));

            provinceColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getProvince()));

            cityColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getCity()));

            levelColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getLevel()));

            dateColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getDate()));

            timeColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getTime()));

            gridStaffColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getGridStaff()));

            reporterColumn.setCellValueFactory(cellData ->
                    new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getReporter()));

            // 初始化模拟数据
            aqiTable.setItems(generateMockData());

            // 设置操作列（详情按钮）
            actionColumn.setCellFactory(param -> new TableCell<AqiData, String>() {
                private final Button detailButton = new Button("详情");

                {
                    detailButton.setOnAction(event -> {
                        AqiData data = getTableView().getItems().get(getIndex());
                        try {
                            FXMLLoader fxmlLoader = new FXMLLoader();
                            URL url = getClass().getResource("../view/AQIAdminStepView.fxml");
                            fxmlLoader.setLocation(url);
                            // 加载视图
                            Parent root = fxmlLoader.load();
                            // 创建对话框
                            Stage dialog = new Stage();
                            dialog.setTitle("AQI数据列表/AQI数据详情");
                            dialog.initModality(Modality.APPLICATION_MODAL);
                            dialog.initOwner(((Node) event.getSource()).getScene().getWindow());
                            // 设置场景并显示
                            Scene scene = new Scene(root);
                            dialog.setScene(scene);
                            // 获取控制器并注入dialog引用（如果需要）
                            AQIAdminStepViewController controller = fxmlLoader.getController();
                            if (controller != null) {
                                controller.setData(data);
                                controller.setDialog(dialog);
                            }
                            // 显示对话框并等待关闭
                            dialog.showAndWait();
                        } catch (IOException ex) {
                            System.err.println("加载FXML文件时出错: " + ex.getMessage());
                            ex.printStackTrace();
                        }
                    });
                }

                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                    } else {
                        setGraphic(detailButton);
                    }
                }
            });
        }

        private ObservableList<AqiData> generateMockData() {
            ObservableList<AqiData> data = FXCollections.observableArrayList();

            for (int i = 1; i <= 10; i++) {
                data.add(new AqiData(
                        String.valueOf(i),
                        getRandomProvince(i),
                        getRandomCity(i),
                        getRandomLevel(i),
                        "2025-06-" + String.format("%02d", i),
                        String.format("%02d", 8 + i % 12) + ":00",
                        "网格员" + i,
                        "反馈者" + i
                ));
            }

            return data;
        }

        // 辅助方法（生成随机数据）
        private String getRandomProvince(int index) {
            String[] provinces = {"北京市", "上海市", "广东省", "江苏省", "浙江省"};
            return provinces[index % provinces.length];
        }

        private String getRandomCity(int index) {
            String[] cities = {"北京市", "上海市", "广州市", "深圳市", "南京市", "杭州市", "苏州市"};
            return cities[index % cities.length];
        }

        private String getRandomLevel(int index) {
            String[] levels = {"优", "良", "轻度污染", "中度污染", "重度污染", "严重污染"};
            return levels[index % levels.length];
        }



        }


}
